<!-- src/views/UserDetailView.vue -->
<template>
  <div class="user-detail-container" v-loading="loading">
    <el-page-header @back="$router.go(-1)" :content="user.username || '加载中...'" style="margin-bottom: 20px;" />

    <el-alert
      v-if="errorMessage"
      :title="errorMessage"
      type="error"
      show-icon
      closable
      style="margin-bottom: 20px;"
    />

    <div v-if="user.id" class="user-profile">
      <el-card class="user-card" shadow="never">
        <template #header>
          <div class="card-header">
            <h2>{{ user.username }} 的个人资料</h2>
          </div>
        </template>
        <div class="user-info">
          <div class="user-avatar-section">
            <el-avatar
              :src="user.avatarUrl || defaultAvatar"
              :size="120"
              shape="circle"
              class="user-avatar"
            />
            <h3>{{ user.nickname || user.username }}</h3>
            <p class="user-username">@{{ user.username }}</p>
            <!-- 新增：粉丝数和关注数统计 -->
            <div class="user-stats">
              <el-statistic :value="user.followerCount" title="粉丝" />
              <el-statistic :value="user.followingCount" title="关注" />
            </div>
             <div v-if="authStore.isAuthenticated && authStore.currentUser?.id !== user.id" class="follow-actions">
              <el-button
                type="primary"
                @click="toggleFollow"
                :loading="followLoading"
                size="small"
              >
                {{ isfollowing ? '取消关注' : '关注' }}
              </el-button>
            </div>
          </div>
          <div class="user-details">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="注册时间">{{ formatDate(user.createdAt) }}</el-descriptions-item>
              <el-descriptions-item label="签名">{{ user.signature || '暂无签名' }}</el-descriptions-item>
              <!-- 可以添加更多用户公开信息，如等级、积分等 (如果后端支持) -->
            </el-descriptions>
          </div>
        </div>
      </el-card>

      <!-- 用户的帖子、回复、收藏等 (可选) -->
      <!-- <div class="user-activity">
        <h3>{{ user.username }} 的活动</h3>
        <el-tabs v-model="activeTab" type="card">
          <el-tab-pane label="帖子" name="posts">
            <PostListView :user-id="Number(userId)" />
          </el-tab-pane>
          <el-tab-pane label="回复" name="replies">
            <ReplyListView :user-id="Number(userId)" />
          </el-tab-pane>
          <el-tab-pane label="收藏" name="favorites">
            <FavoriteListView :user-id="Number(userId)" />
          </el-tab-pane>
        </el-tabs>
      </div> -->
    </div>

    <div v-else-if="!loading" class="user-not-found">
      <p>用户未找到。</p>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
import { getPublicUserInfoById } from '@/services/userService';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';
import {followUser, unfollowUser, isFollowing} from '@/services/userService';

const router = useRouter();
const route = useRoute();
const authStore = useAuthStore();

const loading = ref(false);
const errorMessage = ref('');
const followLoading = ref(false); // 关注按钮加载状态

const user = ref({
  id: null,
  username: '',
  nickname: '',
  avatarUrl: '',
  signature: '',
  createdAt: ''
});



const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'; // Element Plus 默认头像

const userId = computed(() => route.params.id);

// --- 新增: 计算属性判断是否已关注 ---
const isfollowing = ref(false); // 是否已关注目标用户

// 格式化日期
const formatDate = (dateString) => {
  return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss');
};

// --- 新增: 切换关注状态 ---
const toggleFollow = async () => {
  if (!authStore.isAuthenticated) {
    router.push('/login');
    return;
  }
  if (authStore.currentUser?.id === user.value.id) {
    ElMessage.warning('不能关注自己');
    return;
  }

  followLoading.value = true;
  try {
    if (isfollowing.value) {
      await unfollowUser(user.value.id);
      ElMessage.success('取消关注成功');
    } else {
      await followUser(user.value.id);
      ElMessage.success('关注成功');
    }
    // 切换本地状态
    isfollowing.value = !isfollowing.value;
  } catch (error) {
    console.error('Follow/Unfollow user failed:', error);
    ElMessage.error(error.response?.data?.message || '操作失败');
  } finally {
    followLoading.value = false;
  }
};
// --- ---
// 获取用户公开信息
const fetchPublicUserInfo = async () => {
  if (!userId.value) return;
  loading.value = true;
  errorMessage.value = '';
  try {
    const response = await getPublicUserInfoById(userId.value);
    user.value = response.data;
    user.value.avatarUrl = response.data.avatarUrl || defaultAvatar;
     // --- 新增: 获取关注状态 ---
    if (authStore.isAuthenticated && authStore.currentUser?.id !== user.value.id) {
      try {
        const followResponse = await isFollowing(user.value.id);
        isfollowing.value = followResponse.data;
      } catch (followError) {
        console.error('Failed to check follow status:', followError);
        // 可以选择忽略错误或显示警告
        isfollowing.value = false; // 默认未关注
      }
    } else {
      isfollowing.value = false; // 未登录或查看自己，不显示关注按钮
    }
  } catch (error) {
    console.error('Failed to fetch public user info:', error);
    errorMessage.value = error.response?.data?.message || '获取用户信息失败';
    ElMessage.error(errorMessage.value);
    if (error.response?.status === 404) {
      router.push('/404'); // 或者显示 404 页面
    }
  } finally {
    loading.value = false;
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchPublicUserInfo();
});

// 监听路由参数变化 (如果从一个用户详情页导航到另一个)
watch(userId, (newId, oldId) => {
  if (newId && newId !== oldId) {
    fetchPublicUserInfo();
  }
});
</script>

<style scoped>
.user-detail-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.user-profile {
  margin-bottom: 40px;
}

.user-card {
  border: none;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.card-header {
  text-align: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.card-header h2 {
  margin: 0;
  font-size: 1.8em;
  font-weight: bold;
  color: #333;
}

.user-info {
  display: flex;
  flex-wrap: wrap;
  gap: 30px;
  align-items: flex-start;
}

.follow-actions {
  margin-top: 15px;
}
/* *** --- *** */

.user-avatar-section {
  flex: 1;
  min-width: 250px;
  text-align: center;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.user-avatar {
  margin-bottom: 15px;
  border: 2px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
/* *** --- *** */

.user-avatar-section h3 {
  margin: 10px 0 5px 0;
  font-size: 1.5em;
  color: #333;
}

.user-avatar-section p {
  margin: 0;
  color: #666;
  font-size: 0.9em;
}

.user-details {
  flex: 2;
  min-width: 300px;
}

.user-activity {
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.user-activity h3 {
  margin-bottom: 15px;
  color: #333;
}

.user-not-found {
  text-align: center;
  color: #999;
  font-size: 1.2em;
  margin-top: 50px;
}

/* 新增样式 */
.user-stats {
  display: flex;
  justify-content: center;
  gap: 30px;
  margin: 15px 0;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.user-stats .el-statistic {
  text-align: center;
}

.user-stats .el-statistic__head {
  color: #909399;
  font-size: 0.9em;
}

.user-stats .el-statistic__content {
  color: #303133;
  font-size: 1.2em;
  font-weight: 600;
}
</style>
